package com.macro.mall.tiny.modules.oms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.component.wx.WxClient;
import com.macro.mall.tiny.component.wx.entity.bo.WxBO;
import com.macro.mall.tiny.component.wx.entity.bo.WxPayBO;
import com.macro.mall.tiny.component.wx.entity.vo.WxCreateOrderVO;
import com.macro.mall.tiny.modules.oms.model.OmsGood;
import com.macro.mall.tiny.modules.oms.model.OmsOrder;
import com.macro.mall.tiny.modules.oms.model.OmsPromoCode;
import com.macro.mall.tiny.modules.oms.model.dto.CreateOmsOrderDTO;
import com.macro.mall.tiny.modules.oms.model.dto.QueryOmsOrderDTO;
import com.macro.mall.tiny.modules.oms.service.OmsGoodService;
import com.macro.mall.tiny.modules.oms.service.OmsOrderService;
import com.macro.mall.tiny.modules.oms.service.OmsPromoCodeService;
import com.macro.mall.tiny.security.util.MemberContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.cache.CachesEndpoint;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author tyrone
 * @since 2024-10-25
 */
@RestController
@RequestMapping("/oms/omsOrder")
@Api(tags = "OmsOrderController", description = "订单管理")
@Tag(name = "OmsOrderController", description = "订单管理")
public class OmsOrderController {

    private static final Logger log = LoggerFactory.getLogger(OmsOrderController.class);
    @Autowired
    private OmsOrderService omsOrderService;

    @Autowired
    private OmsGoodService omsGoodService;
    @Autowired
    private OmsPromoCodeService  promoCodeService;

    public static Map<Integer,OmsGood> goodMap = new HashMap<>();;

    @PostConstruct
    public void init(){
        goodMap = omsGoodService.list().stream().collect(Collectors.toMap(OmsGood::getId, omsGood -> omsGood));
    }

    public static Map<Integer, OmsGood> getGoodMap() {
        return goodMap;
    }



    @Autowired
    private WxClient wxClient;

    @ApiOperation(value = "创建订单")
    @PostMapping()
    public CommonResult<WxCreateOrderVO> pay(@RequestBody @Validated CreateOmsOrderDTO createOmsOrderDTO) {
        if (!createOmsOrderDTO.getOpenId().equals(MemberContext.getMember().getOpenId())) {
            return CommonResult.failed("非法操作");
        }
        try {
            if (StringUtils.isNotEmpty(createOmsOrderDTO.getPromoCode())){
                OmsPromoCode promoCode = promoCodeService.query().eq("promo_code", createOmsOrderDTO.getPromoCode()).eq("status", 1).one();
                if (promoCode == null || promoCode.getOpenId().equals(createOmsOrderDTO.getOpenId())){
                    return CommonResult.failed("优惠码无效");
                }
            }
            OmsOrder order = omsOrderService.createOrder(createOmsOrderDTO);
            log.info("created order:{}", order);
            WxPayBO wxPayBO = order.buildWxPayBO();
            WxBO wxBO = wxClient.buildOrder(wxPayBO);
            if (wxBO.getSuccess()) {
                return CommonResult.success(wxBO.convertToCreateOrderVO());
            }
            return CommonResult.failed(wxBO.getErrorMsg());
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }


    @ApiOperation(value = "前台分页查看订单")
    @PostMapping("/page")
    public CommonResult<IPage<OmsOrder>> page(@RequestBody QueryOmsOrderDTO dto) {
        if (MemberContext.getMember() == null) {
            return CommonResult.failed("请先登录");
        }
        QueryWrapper<OmsOrder> query = new QueryWrapper<>();
        String openId = MemberContext.getMember().getOpenId();
        query.eq("open_id", openId);
        if (dto.getStatus() != null) {
            query.eq("status", dto.getStatus());
        }
        if (dto.getCreateTimeStart() != null) {
            query.ge("create_time", dto.getCreateTimeStart());
        }
        if (dto.getCreateTimeEnd() != null) {
            query.le("create_time", dto.getCreateTimeEnd());
        }
        if (StringUtils.isNotEmpty(dto.getGoodName())) {
            List<OmsGood> name = omsGoodService.query().like("name", dto.getGoodName()).list();
            query.in("good_id", name.stream().map(OmsGood::getId).collect(Collectors.toList()));
        }
        query.orderByDesc("create_time");
        Page<OmsOrder> page = omsOrderService.page(new Page<>(dto.getPageNum(), dto.getPageSize(), true), query);
        page.getRecords().forEach(omsOrder -> omsOrder.setGoods(Lists.newArrayList(goodMap.get(omsOrder.getGoodId()))));
        return CommonResult.success(page);

    }

    @ApiOperation(value = "后台万能分页查看订单")
    @PostMapping("/admin/page")
    public CommonResult<IPage<OmsOrder>> adminPage(@RequestBody QueryOmsOrderDTO dto) {
        QueryWrapper<OmsOrder> query = new QueryWrapper<>();
        if (dto.getStatus() != null) {
            query.eq("status", dto.getStatus());
        }
        if (dto.getCreateTimeStart() != null) {
            query.ge("create_time", dto.getCreateTimeStart());
        }
        if (dto.getCreateTimeEnd() != null) {
            query.le("create_time", dto.getCreateTimeEnd());
        }
        if (StringUtils.isNotEmpty(dto.getOpenId())) {
            query.eq("open_id", dto.getOpenId());
        }
        if (StringUtils.isNotEmpty(dto.getGoodName())) {
            List<OmsGood> name = omsGoodService.query().like("name", dto.getGoodName()).list();
            query.in("good_id", name.stream().map(OmsGood::getId).collect(Collectors.toList()));
        }
        if (StringUtils.isNotEmpty(dto.getOrderId())){
            query.eq("order_id",dto.getOrderId());
        }
        query.orderByDesc("create_time");
        Page<OmsOrder> page = omsOrderService.page(new Page<>(dto.getPageNum(), dto.getPageSize(), true), query);
        page.getRecords().forEach(omsOrder -> omsOrder.setGoods(Lists.newArrayList(goodMap.get(omsOrder.getGoodId()))));
        return CommonResult.success(page);
    }


}

